import { NextResponse } from "next/server";
import { db } from "@/lib/db";

// reg
export async function POST(request) {
    const res = await request.json();
    const checkUserSql = `SELECT 1 FROM users WHERE username = '${res.username}'`;

    try {
        await new Promise((resolve, reject) => {
            db.query(checkUserSql, (err, results) => {
                if (err) {
                    reject(err);
                } else {
                    if (results.length === 0) {
                        const insertUserSql = `INSERT INTO users (username, password) VALUES ('${res.username}', '${res.password}')`;
                        db.query(insertUserSql, (err, results) => {
                            if (err) {
                                reject(err);
                            } else {
                                resolve(results);
                            }
                        });
                    } else {
                        reject("用户名已经被注册了");
                    }
                }
            });
        });

        return NextResponse.json({ msg: "注册成功", status: 200 });
    } catch (error) {
        return NextResponse.json({ msg: error, status: 500 });
    }
}
